﻿using AutoMapper;
using MediatR;
using NPOI.OpenXmlFormats;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PrenatalCheckup
{
    /// <summary>
    /// 修改种母妊检
    /// </summary>
    public class UpdatePrenatalCheckupHandler : IRequestHandler<UpdatePrenatalCheckupCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 种母妊检仓储
        /// </summary>
        private readonly IBaseRepository<PrenatalCheckups> _prenatalCheckupsRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdatePrenatalCheckupHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="prenatalCheckupsRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public UpdatePrenatalCheckupHandler(IBaseRepository<PrenatalCheckups> prenatalCheckupsRepository,
                                            ILogger<UpdatePrenatalCheckupHandler> logger,
                                            IMapper mapper)
        {
            _prenatalCheckupsRepository = prenatalCheckupsRepository;
            _logger = logger;
            _mapper = mapper;
        }


        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UpdatePrenatalCheckupCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Updated };
            try
            {
                //修改条件存入map
                request.PregnancyTestDate = request.PregnancyTestDate.Value.AddHours(8);
                request.UpdateTime = DateTime.Now;
                var prenatal = _mapper.Map<PrenatalCheckups>(request);
                var res = await _prenatalCheckupsRepository.Update(prenatal);
                //判断
                if (res > 0)
                {
                    result.Msg = "修改种母妊检成功";
                    result.Code = (int)CommonErrorCode.Success;
                }
            }
            catch (Exception ex)
            {
                result.Msg = "修改种母妊检异常" + ex.Message;
                _logger.LogError("修改种母妊检异常" + ex.Message);
            }
            return result;
        }
    }
}
